#include"fraction.h"
#include<math.h>
using namespace std;

fraction::fraction(int nume, int deno) {//
    numerator = nume;
    denominator = deno;
}

fraction fraction::gcdlcm(int _a, int _b) {
    int GCD, LCM, GCD1[100], GCD2[100], k = 0, p, q;
    int a = abs(_a), b = abs(_b);
    int sign = 1;
    if (_a * _b < 0) {
        sign = -1;
    }

    fraction x;
    for (int j = 1; j < a; j++) {
        if (a % j == 0) {
            GCD1[k] = j;
            k++;
        }
    }
    p = k;
    k = 0;
    for (int j = 1; j < b; j++) {
        if (b % j == 0) {
            GCD2[k] = j;
            k++;
        }
    }
    q = k;
    for (int m = 1; m <= p; m++) {
        for (int n = 1; n <= q; n++) {
            if (GCD1[m - 1] == GCD2[n - 1]) {
                GCD = GCD1[m - 1];
            }
        }
    }
    if (a % b == 0) {
        GCD = b;
    }
    if (b % a == 0) {
        GCD = a;
    }
    LCM = a * b / GCD;
    x.numerator = GCD;
    x.denominator = sign*LCM;
    return x;
}

fraction fraction::operator+(fraction a) {
    fraction d = gcdlcm(a.denominator, this->denominator);
    fraction f;
    f.denominator = d.denominator;
    f.numerator = a.numerator * (f.denominator / a.denominator) + this->numerator * (f.denominator / this->denominator);
    fraction e = gcdlcm(f.numerator, f.denominator);
    f.denominator /= e.numerator;
    f.numerator /= e.numerator;
    return f;
}

fraction fraction::operator-(fraction a) {
    fraction d = gcdlcm(a.denominator, this->denominator);
    fraction f;
    f.denominator = d.denominator;
    f.numerator = this->numerator * (f.denominator / this->denominator) - a.numerator * (f.denominator / a.denominator);
    fraction e = gcdlcm(f.numerator, f.denominator);
    f.denominator /= e.numerator;
    f.numerator /= e.numerator;
    return f;
}

fraction fraction::operator*(fraction a) {
    fraction f;
    f.denominator = this->denominator * a.denominator;
    f.numerator = this->numerator * a.numerator;
    return f.simplify();
}

fraction fraction::operator/(fraction a) {
    fraction f;
    f.denominator = this->denominator * a.numerator;
    f.numerator = this->numerator * a.denominator;
    return f.simplify();
}

void fraction::print() {
    if (numerator % denominator == 0) {
        cout << numerator / denominator;
    }
    else {
        cout << numerator << "/" << denominator;
    }
}

fraction fraction::simplify() {
    int gcd = gcdlcm(this->numerator, this->denominator).numerator;
    this->numerator /= gcd;
    this->denominator /= gcd;
    return *this;
}
